package com.heima.kafka.sample;

import org.apache.kafka.clients.producer.*;
import org.apache.kafka.common.serialization.StringSerializer;

import java.util.Properties;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 * @author brianxia
 * @version 1.0
 * @date 2022-10-25 10:43
 */
public class ProducerQuickStart107 {

    public static void main(String[] args) {

        //构建properties对象，对kafka进行配置
        Properties properties = new Properties();
        //kafka地址
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG,"192.168.200.130:9092");
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        properties.put(ProducerConfig.ACKS_CONFIG,"all");
        //重试次数
        properties.put(ProducerConfig.RETRIES_CONFIG,10);
        //数据压缩
        properties.put(ProducerConfig.COMPRESSION_TYPE_CONFIG,"lz4");

        //创建kafka生产者对象
        KafkaProducer<String, String> producer =
                new KafkaProducer<String, String>(properties);

        for (int i = 0; i < 10; i++) {

            //投递消息
            ProducerRecord<String, String> producerRecord =
                    new ProducerRecord<String, String>("itcast-107-3",String.valueOf(i),"hello world" + i);

            //同步非阻塞
            Future<RecordMetadata> send = producer.send(producerRecord);

            //干别的事情

            //
            try {
                System.out.println(Thread.currentThread().getName());
                RecordMetadata recordMetadata = send.get();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }

            //异步
            producer.send(producerRecord, (metadata, exception) -> {
                //当前数据返回了，处理
                System.out.println(Thread.currentThread().getName());
                System.out.println(metadata);
                if(exception != null){
                    //记录日志或者数据库
                }
            });
        }


        producer.close();
    }
}
